<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>使用XML完成数据交换</title>
</head>
<body>
<script type="text/javascript">
  window.onload =function (){
    document.getElementById("btn").onclick = function (){
      //1.创建ajax核心对象
      var xhr = new XMLHttpRequest()
      //2.注册回调函数
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status == 200) {
            //服务器端响应了一个XML字符串，怎么接收呢？
            //使用XMLHttpRequest对象的responseXML属性，接收之后，可以自动封装成document对象（文档对象）
            var xmlDoc = this.responseXML
            //console.log(xmlDoc)
            var students = xmlDoc.getElementsByTagName("student")
            var html = ""
            for(var i = 0; i < students.length; i++){
              var  student = students[i]
              //获取<student>元素下的所有子元素
              var nameOrAge = student.childNodes
              html += "<tr>"
              html += "<td>"+(i+1)+"</td>"
              for(var j = 0; j < nameOrAge.length; j++){
                var node = nameOrAge[j]
                if (node.nodeName == "name") {
                  //console.log("name="+node.textContent)
                     html += "<td>" + node.textContent + "</td>"
                  //content 内容
                }
                if (node.nodeName == "age") {
                     html += "<td>" + node.textContent + "</td>"
                }
              }
              html += "</tr>"
            }
            document.getElementById("stubody").innerHTML = html
          }else{
            alert(this.status)
          }
        }
      }
      //3.开启通道
      xhr.open("GET","/ajax02/ajax_xmlTest?t="+ new Date().getTime(),true)
      //4.发送请求
      xhr.send()
    }
  }
</script>

<button id="btn">显示学生列表</button>
<table width="500px" border="1px">
  <thead>
    <tr>
      <th>序号</th>
      <th>姓名</th>
      <th>年龄</th>
    </tr>
  </thead>
  <tbody id="stubody">
<!--    <tr>-->
<!--      <td>1</td>-->
<!--      <td>zhangsan</td>-->
<!--      <td>20</td>-->
<!--    </tr>-->


  </tbody>
</table>
</body>
</html>